﻿using System.Collections.Generic;
using System.Threading;

namespace RedRiver.Framework.XtraCommon.FastReflection{
    public abstract class FastReflectionCache<TKey, TValue> : IFastReflectionCache<TKey, TValue>{
        private readonly Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();
        private object _syncRoot;

        public virtual object SyncRoot{
            get{
                if (_syncRoot == null){
                    Interlocked.CompareExchange(ref _syncRoot, new object(), null);
                }
                return _syncRoot;
            }
        }

        #region IFastReflectionCache<TKey,TValue> Members

        public TValue Get(TKey key){
            TValue value = default(TValue);
            if (_cache.TryGetValue(key, out value)){
                return value;
            }

            lock (SyncRoot){
                if (!_cache.TryGetValue(key, out value)){
                    value = Create(key);
                    _cache[key] = value;
                }
            }

            return value;
        }

        #endregion

        protected abstract TValue Create(TKey key);
    }
}